package org.iweb.fs.company;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

import org.iweb.db.company.CompanyVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CompanyFactory {

	private Logger log = LoggerFactory.getLogger(CompanyFactory.class);
	private static CompanyFactory _instance;
	private File baseFolder;
	private File baseTemplateFolder;

	private CompanyFactory() {
		try {
			baseFolder = new File("/Users/zanottom/Documents/E/projects/test/iweb/WebContent/pages");
			if (!baseFolder.exists())
				baseFolder.createNewFile();
			baseTemplateFolder = new File("/Users/zanottom/Documents/E/projects/test/iweb/WebContent/template/company");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static CompanyFactory getInstance() {
		if (_instance == null)
			_instance = new CompanyFactory();
		return _instance;
	}

	public void createStructure(CompanyVO companyVO) {
		try {
			File root = new File(baseFolder, companyVO.getName());
			root.mkdir();

			File destFile = null;

			for (File f : baseTemplateFolder.listFiles()) {
				destFile = new File(root, f.getName());
				copyFile(f, destFile);
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void copyFile(File sourceFile, File destFile)
			throws IOException {
		if (!destFile.exists()) {
			destFile.createNewFile();
		}

		FileChannel source = null;
		FileChannel destination = null;
		try {
			source = new FileInputStream(sourceFile).getChannel();
			destination = new FileOutputStream(destFile).getChannel();
			destination.transferFrom(source, 0, source.size());
		} finally {
			if (source != null) {
				source.close();
			}
			if (destination != null) {
				destination.close();
			}
		}
	}

}
